package cn.zl.ymcc.controller;

import cn.zl.ymcc.entity.MediaFile;
import cn.zl.ymcc.query.MediaFileQuery;
import cn.zl.ymcc.result.PageResult;
import cn.zl.ymcc.result.Result;
import cn.zl.ymcc.service.MediaFileService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zl
 * @since 2025-10-24
 */
@RestController
@RequestMapping("/mediaFile")
@Slf4j
public class MediaFileController {

    @Autowired
    private MediaFileService mediaFileService;


    //===============================================================
//文件注册，检查文件是否已经上传
    @PostMapping("/register")
    public Result register(@RequestParam("fileMd5") String fileMd5,     // 文件唯一标识
                           @RequestParam("fileName") String fileName,   // 文件名
                           @RequestParam("fileSize") Long fileSize,     // 文件大小
                           @RequestParam("mimetype") String mimetype,   // mime类型
                           @RequestParam("fileExt") String fileExt) {   //文件扩展名

        log.info("文件上传-文件注册,fileName={},fileMd5={}", fileName, fileMd5);

        return mediaFileService.register(fileMd5, fileName, fileSize, mimetype, fileExt);
    }

    //校验文件块是否已经存在了
    @PostMapping("/checkchunk")
    public Result checkchunk(
            // 文件唯一标识
            @RequestParam("fileMd5") String fileMd5,
            // 当前分块下标
            @RequestParam("chunk") Integer chunk,
            // 当前分块大小
            @RequestParam("chunkSize") Integer chunkSize) {
        log.info("文件上传-检查文件块是否存在；{}", fileMd5);
        return mediaFileService.checkchunk(fileMd5, chunk, chunkSize);
    }

    //上传分块后的文件
    @PostMapping("/uploadchunk")
    public Result uploadchunk(
            //分块后的文件
            @RequestParam("file") MultipartFile file,
            // 文件唯一标识
            @RequestParam("fileMd5") String fileMd5,
            // 第几块，分块的索引
            @RequestParam("chunk") Integer chunk) {

        log.info("文件上传 fileName={},fileMd5={}", file.getOriginalFilename(), fileMd5);
        return mediaFileService.uploadchunk(file, fileMd5, chunk);
    }

    //分块都上传成功之后，合并分块
    @PostMapping("/mergechunks")
    public Result mergechunks(
            // 课程章节ID
            @RequestParam("chapterId") Long chapterId,
            // 课程ID
            @RequestParam("courseId") Long courseId,
            // 课程序列号
            @RequestParam("videoNumber") Integer videoNumber,
            // 课程章节ID
            @RequestParam("name") String name,
            //章节名
            @RequestParam("chapterName") String chapterName,
            //课程名
            @RequestParam("courseName") String courseName,
            // 文件唯一标识
            @RequestParam("fileMd5") String fileMd5,
            // 源文件名
            @RequestParam("fileName") String fileName,
            // 文件总大小
            @RequestParam("fileSize") Long fileSize,
            // 文件的mimi类型
            @RequestParam("mimetype") String mimetype,
            // 文件扩展名
            @RequestParam("fileExt") String fileExt) {

        log.info("合并文件 fileName={} ，fileMd5={} ", fileName, fileMd5);
        return mediaFileService.mergechunks(fileMd5, fileName, fileSize, mimetype, fileExt, chapterId, courseId, videoNumber, name, courseName, chapterName);
    }

//===============================================================


    @Operation(summary = "创建")
    @PostMapping
    public Result<Boolean> save(@RequestBody MediaFile mediaFile) {
        boolean result = mediaFileService.save(mediaFile);
        return result ? Result.success() : Result.error("创建失败");
    }

    @Operation(summary = "更新")
    @PutMapping
    public Result<Boolean> update(@RequestBody MediaFile mediaFile) {
        boolean result = mediaFileService.updateById(mediaFile);
        return result ? Result.success() : Result.error("更新失败");
    }

    @Operation(summary = "删除")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@Parameter(description = "ID", required = true) @PathVariable Long id) {
        boolean result = mediaFileService.removeById(id);
        return result ? Result.success() : Result.error("删除失败");
    }

    @Operation(summary = "根据ID查询")
    @GetMapping("/{id}")
    public Result<MediaFile> findById(@Parameter(description = "ID", required = true) @PathVariable Long id) {
        MediaFile mediaFile = mediaFileService.getById(id);
        return mediaFile != null ? Result.success(mediaFile) : Result.error("数据不存在");
    }

    @Operation(summary = "查询所有")
    @GetMapping("/list")
    public Result<List<MediaFile>> findAll() {
        List<MediaFile> list = mediaFileService.list();
        return Result.success(list);
    }


    @Operation(summary = "分页查询")
    @PostMapping("pagelist")
    public Result<PageResult<MediaFile>> findPage(
            @RequestBody MediaFileQuery query){
        Page<MediaFile> page = new Page<>(query.getPage(), query.getRows());
        QueryWrapper<MediaFile> queryWrapper = new QueryWrapper<>();

        IPage<MediaFile> pageResult = mediaFileService.page(page, queryWrapper);
        PageResult<MediaFile> result = PageResult.build(
                pageResult.getTotal(), pageResult.getRecords(), query.getPage(), query.getRows());
        return Result.success(result);
    }

}